﻿using System;
using Confluent.Kafka;
using JT808.Gateway.Abstractions;
using JT808.Gateway.Kafka.Configs;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace JT808.Gateway.Kafka
{
    public class JT808ApiResponseProducer : IJT808ApiResponseProducer
    {
        private bool disposed = false;
        public string TopicName { get; }

        private readonly IProducer<string, byte[]> producer;

        private readonly ILogger logger;

        public JT808ApiResponseProducer(ILoggerFactory loggerFactory,
          IOptions<JT808ApiResponseProducerConfig> producerConfigAccessor)
        {
            logger = loggerFactory.CreateLogger<JT808MsgProducer>();
            producer = new ProducerBuilder<string, byte[]>(producerConfigAccessor.Value).Build();
            TopicName = producerConfigAccessor.Value.TopicName;
        }
        private void Dispose(bool disposing)
        {
            if (disposed) return;
            if (disposing)
            {
                producer.Dispose();
            }
            disposed = true;
        }

        public void Dispose()
        {
            //必须为true
            Dispose(true);
            //通知垃圾回收机制不再调用终结器（析构器）
            GC.SuppressFinalize(this);
        }

        ~JT808ApiResponseProducer() { Dispose(false); }

        public async void ProduceAsync(string notifyKey, byte[] param)
        {
            if (disposed) return;
            try
            {
                await producer.ProduceAsync(TopicName, new Message<string, byte[]>
                {
                    Key = notifyKey,
                    Value = param
                });
                logger.LogDebug($"A message has been produced with key={notifyKey} and value={param}");
            }
            catch (AggregateException ex)
            {
                logger.LogError(ex, "kafka error");
            }
        }
    }
}
